package cn.ncu.controller;

import cn.ncu.entity.Result;
import cn.ncu.entity.User;
import cn.ncu.service.UserService;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;

/**
 * @author:Martina
 * @create:2020-07-09 10:46
 * @description:
 */
@Controller
@RequestMapping("user")
@CrossOrigin
public class UserController {

    @Autowired
    public DefaultKaptcha defaultKaptcha;

    @Autowired
    private UserService userService;

    /**
     * 生成验证码
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping("/defaultKaptcha")
    public void defaultKaptcha(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        byte[] captchaChallengeAsJpeg = null;
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
        try {
            // 生产验证码字符串并保存到session中
            String createText = defaultKaptcha.createText();
            request.getSession().setAttribute("rightCode", createText);
            // 使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
            BufferedImage challenge = defaultKaptcha.createImage(createText);
            ImageIO.write(challenge, "jpg", jpegOutputStream);
        } catch (IllegalArgumentException e) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        // 定义response输出类型为image/jpeg类型，使用response输出流输出图片的byte数组
        captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
        response.setHeader("Cache-Control", "no-store");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");
        ServletOutputStream responseOutputStream = response.getOutputStream();
        responseOutputStream.write(captchaChallengeAsJpeg);
        responseOutputStream.flush();
        responseOutputStream.close();
    }

    /**
     * 验证
     * @param user
     * @param
     * @param code
     * @return
     */
    @PostMapping("/check")
    @ResponseBody
    public Result imgvrifyControllerDefaultKaptcha(String code, @RequestBody User user, HttpSession session) {
        Result result = new Result();
        String rightCode = (String) session.getAttribute("rightCode");
        if(!rightCode.equals(code)){
            result.setMessage("验证码错误呦！");
        }else{
            if(userService.findByUserName(user.getUsername())==null){
                userService.save(user);
                result.setFlag(true).setMessage("注册成功，快去登录吧！");
            }else{
                result.setMessage("用户名已存在！");
            }
        }
        return result;
    }

    @PostMapping("login")
    @ResponseBody
    public Result login(@RequestBody User user, HttpServletRequest request){
        Result result = new Result();
        User oneUser = userService.findOneUser(user);
        if(oneUser!=null){
            result.setFlag(true);
//            request.getServletContext().setAttribute(user.getId(),user);
        }else{
            result.setMessage("用户名或密码错误，请重新尝试！");
        }
        return result;
    }
}
